package com.cb2.algorithm.leetcode;

/**
 * <a href="https://leetcode.cn/problems/move-zeroes/">移动零(Move Zeros)</a>
 * <p>给定一个数组 nums，编写一个函数将所有 0 移动到数组的末尾，同时保持非零元素的相对顺序。</p>
 * <p>请注意 ，必须在不复制数组的情况下原地对数组进行操作。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1:
 *      输入: nums = [0,1,0,3,12]
 *      输出: [1,3,12,0,0]
 *
 * 示例 2:
 *      输入: nums = [0]
 *      输出: [0]
 * </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *  <ul>
 *     <li>1 <= nums.length <= 10^4</li>
 *     <li>-2^31 <= nums[i] <= 2^31 - 1</li>
 *  </ul>
 * </p>
 * <b>进阶：你能尽量减少完成的操作次数吗？</b>
 *
 * @author c2b
 * @since 2023/10/31 9:59
 */
public class LC0283MoveZeroes_S {

    static class Solution {
        public void moveZeroes(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return;
            }
            // 下一个非0数字应该在的位置
            int nextNonZeroTargetIndex = 0;
            for (int currIndex = 0; currIndex < nums.length; currIndex++) {
                //当前元素!=0，就把其交换到左边，等于0的交换到右边
                if (nums[currIndex] != 0) {
                    int temp = nums[currIndex];
                    nums[currIndex] = nums[nextNonZeroTargetIndex];
                    nums[nextNonZeroTargetIndex] = temp;
                    ++nextNonZeroTargetIndex;
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] ints = {0, 1, 0, 3, 12};
        solution.moveZeroes(ints);
        Printer.printArrayInt(ints);
    }
}